package com.scalar.chiptrack.operations.finishedGoods.actionCommands;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.operations.finishedGoods.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.finishedGoods.forms.FinishedGoodsEntryForm;

/**
 * User: Murali Krishna Yengala
 * Date: Jun 6, 2005
 * Time: 1:00:49 PM
 */
public class FinishedGoodsSaveAlgorithmCommand extends ChipTrackExtendedAction {
    
    public ActionForward executeRequest( ActionMapping mapping,
                                         ActionForm form,
                                         HttpServletRequest request,
                                         HttpServletResponse response) throws Exception
    {
        HashMap errors              = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
        HashMap info                = ( HashMap ) request.getAttribute( INFO_MESSAGES );
        FinishedGoodsEntryForm finishedGoodsEntryForm = ( FinishedGoodsEntryForm ) form;
		try
        {
            String algorithmName = request.getParameter("algorithmName");
            algorithmName = algorithmName == null ? "" : algorithmName.trim();
            if( !("".equals( algorithmName)))
            {
                int algorithmId = FinishedGoodsDAO.getAlgorithmId( algorithmName);
                if( algorithmId != -1 )
                {
                    errors.put("Algorithm = "+algorithmName, " exists");
                }
                else
                {
                    algorithmId = FinishedGoodsDAO.saveAlgorithmName( null,  algorithmName );
                    info.put("Algorithm = "+algorithmName, " saved successfully");
                }
            }
            else
            {
                errors.put("Invalid Algorithm !", null);
            }
       	}
        catch ( Exception e )
        {
            e.printStackTrace();
            errors.put( ERROR_INTERNAL_SERVER_ERROR, "While saving Algorithm " );
        }
		request.setAttribute( ERROR_MESSAGES, errors );
		request.setAttribute( INFO_MESSAGES, info );
        return mapping.findForward("addAlgorithm");
    }
}
